package com.shuguang.medicalcare;

import static java.lang.Thread.sleep;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class Detail extends AppCompatActivity {
    public Button back;
    public String id;
    public String caller;
    public String mobile;

    public TextView customInfo;
    public JSONObject cInfo;

    public Button netCall;
    public Button addWX;

    public LinearLayout giftBox;
    public LinearLayout giftList;

    public RadioGroup rg;

    public LinearLayout otherBox;
    public LinearLayout otherTitle;


    public  int index;
    public JSONObject item=null;

    public Boolean giftb=false;
    public Boolean otherb=false;


    public Button phoneCall;
//    Boolean


    public Context temContext;

    public Button submitBtn;

    public String isC="0";
    public String timeT="3";
    public String mydate="";
    public EditText memo;

    public  TextView checkNum;

    public TextView timePicker;
    public String err;

    int mYear;
    int mMonth;
    int mDay;

    int count;

    public ProgressDialog p;


    public CountDownTimer timer;

    public String isAutoDial;
    public String isRefreshList;
    public int countDownSeconds;

    private mHandler mHandler = new mHandler(this);


    //    Handle 静态内部类 防止内存泄漏
    private static class mHandler extends Handler {
        WeakReference<Detail> weakReference;
        public mHandler(Detail mainActivity){
            weakReference = new WeakReference<Detail>(mainActivity);
        }
        @Override
        public void handleMessage(Message msg){
            Detail mainActivity = weakReference.get();
            if(mainActivity != null){
                try {
                    if(msg.what == 4){
                        mainActivity.toastNetCall();
                    }
                    if(msg.what==2){
                        mainActivity.toast();
                    }else {
                        mainActivity.render();
                    }
                } catch (JSONException | InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    private void toastNetCall() throws InterruptedException {

//        ProgressDialog p=new ProgressDialog(getApplicationContext());
//        p.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//
//        p.setMessage(err);
//        p.setCancelable(false);
//        p.show();

//        sleep(500);

//        p.hide();
        p.dismiss();

        Toast.makeText(Detail.this, err, Toast.LENGTH_SHORT).show();

    }

    public void toast() throws JSONException, InterruptedException {
        p.dismiss();

        Toast.makeText(Detail.this, "操作完成!", Toast.LENGTH_SHORT).show();
//        更新数据
        SharedPreferences sp =getSharedPreferences("userinfo",MODE_PRIVATE);
        String str= sp.getString("list","");
        JSONArray arr = new JSONArray(str);

        Log.i("错误999", arr.toString());

        for (int i=0;i<arr.length();i++){
            if(id.equals(arr.getJSONObject(i).getString("id"))){
                arr.getJSONObject(i).put("finishState",true);
            }
        }

        SharedPreferences sp1 =getSharedPreferences("userinfo",MODE_PRIVATE);
        SharedPreferences.Editor ed =sp1.edit();
        ed.putString("list",arr.toString());
        ed.commit();




//        urlBuilder.addQueryParameter("hosId", "1");
//        urlBuilder.addQueryParameter("taskId" ,taskId);
//        urlBuilder.addQueryParameter("groupId",sp.getString("groupId",""));
//        urlBuilder.addQueryParameter("userId", sp.getString("userId",""));
//        urlBuilder.addQueryParameter("managerId", sp.getString("managerId",""));



//        finish();



//        requestDetail();

        //        若自动拨号打开 加载下一条数据 倒计时
                    String isA= sp.getString("isAutoDial","0");
                    String isR = sp.getString("isRefreshList","0");
                    String count = sp.getString("countDownSeconds","5");

                    if(isA.equals("1")){
                        netCall.setClickable(false);
                        if(isR.equals("0")){
                            //获取 是否 有 可用的数据
                            ArrayList list= getNextAble();
                            if(list.size()>0){

                                id= new JSONObject(list.get(0).toString()).getString("id");
                                mobile= new JSONObject(list.get(0).toString()).getString("mobile");
                                requestDetail();

                                submitBtn.setClickable(false);
                                netCall.setClickable(false);
                                timer.start();


                                giftb=false;
                                otherb=false;

                                Log.i("可用的数据", list.get(0).toString());
//
                                // 有自动刷新 许在 计时器 完成 回访接口调用

//                                this.netCallback();

                            }
                            else{


                                SharedPreferences sp2 =getSharedPreferences("uerinfo",MODE_PRIVATE);
                                SharedPreferences.Editor ed2 =sp.edit();
                                ed2.putString("list","");
                                ed2.commit();
                                submitBtn.setClickable(false);
                                submitBtn.setText("该科室项目已全部操作完,返回列表自动刷新!");
                                finish();
                            }

                        }else{

                            ArrayList list= getNextAble();
                            if(list.size()>0){
                                id= new JSONObject(list.get(0).toString()).getString("id");
                                mobile= new JSONObject(list.get(0).toString()).getString("mobile");
                                requestDetail();

                                submitBtn.setClickable(false);
                                netCall.setClickable(false);
                                timer.start();

                                //       有自动刷新 许在 计时器 完成 回访接口调用
//                                this.netCallback();

                                giftb=false;
                                otherb=false;

                                Log.i("可用的数据", id);
//


                            }else{


                                SharedPreferences sp2 =getSharedPreferences("uerinfo",MODE_PRIVATE);
                                SharedPreferences.Editor ed2 =sp.edit();
                                ed2.putString("list","");
                                ed2.commit();
                                submitBtn.setClickable(false);
                                submitBtn.setText("该科室项目已全部操作完,返回列表自动刷新!");
                                finish();
                            }





                        }

                    }

                    if(isR.equals("1")){
                        if(isA.equals("0")){


                            ArrayList list= getNextAble();
                            if(list.size()==0){
                                SharedPreferences sp2 =getSharedPreferences("uerinfo",MODE_PRIVATE);
                                SharedPreferences.Editor ed2 =sp.edit();
                                ed2.putString("list","");
                                ed2.commit();
                                submitBtn.setClickable(false);
                                netCall.setClickable(false);
                                submitBtn.setText("该科室项目已全部操作完,返回列表自动刷新!");
                            }else {
                                submitBtn.setClickable(false);
                                netCall.setClickable(false);
                                submitBtn.setText("提交成功");
                            }

                        }



                    }

                    if(isA.equals("0")){
                        if(isR.equals("0")){
                            finish();
                        }
                    }

        /**
         * 区分 哪些是完成的  哪些是未完成的
         */





//        打开刷新列表 情况 JSONArr 自动刷新 下一组



//        SharedPreferences sp2 =getSharedPreferences("userinfo",MODE_PRIVATE);
//        requestDetail();
//        finish();

    }
    public ArrayList getNextAble() throws JSONException {

        SharedPreferences sp =getSharedPreferences("userinfo",MODE_PRIVATE);
        String str= sp.getString("list","");
        JSONArray arr = new JSONArray(str);

        for (int i=0;i<arr.length();i++){
            if(id.equals(arr.getJSONObject(i).getString("id"))){
                arr.getJSONObject(i).put("finishState",true);
            }
        }

          ArrayList list =new ArrayList();
          for(int i=0;i<arr.length();i++){
              if(!arr.getJSONObject(i).getBoolean("finishState")){
//                  temp.add(arr.getJSONObject(i));
                  list.add(arr.getJSONObject(i));
              }
          }

          return list;






    }

    @SuppressLint("WrongConstant")
    public void render() throws JSONException {
        customInfo.setText( cInfo.getString("call_name"));
        checkNum.setText( "号码状态: "+ cInfo.getString("checkstatusname"));
        int len=  cInfo.getJSONArray("gift_type").length();
        giftBox= (LinearLayout)findViewById(R.id.giftBox);
        giftList= (LinearLayout)findViewById(R.id.giftListTitle);
        if(len == 0){

           giftBox.setVisibility(8);
           giftList.setVisibility(8);
        }else {
            giftBox.setVisibility(0);
            giftList.setVisibility(0);

            renderGiftList();
        }


        otherBox= (LinearLayout)findViewById(R.id.other);
        otherTitle= (LinearLayout)findViewById(R.id.otherTitle);
        if(len == 0){

            otherBox.setVisibility(8);
            otherTitle.setVisibility(8);
        }else {
            otherBox.setVisibility(0);
            otherTitle.setVisibility(0);

            renderOtherList();
        }


        for(int m1=0;m1<giftBox.getChildCount();m1++){
            View viewchild = giftBox.getChildAt(m1);

            CheckBox cb =viewchild.findViewById(R.id.cb);

            final int mis=m1;
            cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        giftb=true;
                        otherb=false;
                        index=mis;
                        for (int l=0;l<giftBox.getChildCount();l++){
                            if(index == l){
                                JSONArray arr= null;
                                try {
                                    arr = cInfo.getJSONArray("gift_type");
                                    item= arr.getJSONObject(index);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            } else {
                                View c1=giftBox.getChildAt(l);
                                CheckBox b1 =c1.findViewById(R.id.cb);
                                b1.setChecked(false);
                            }
                        }


                        for(int j=0;j<otherBox.getChildCount();j++){
                            View vc = otherBox.getChildAt(j);
                            CheckBox cb =vc.findViewById(R.id.cb);
                            cb.setChecked(false);
                        }
                    }
                }
            });
        }


        for(int m=0;m<otherBox.getChildCount();m++){
            View vc = otherBox.getChildAt(m);

            CheckBox cb =vc.findViewById(R.id.cb);

            final int mi=m;
            cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        otherb=true;
                        giftb=false;
                        index=mi;

                        for (int k=0;k<otherBox.getChildCount();k++){
                            if(index == k){
//                                gift_type  no_gift_type
                                JSONArray arr= null;
                                try {
                                     arr=   cInfo.getJSONArray("no_gift_type");
                                   item= arr.getJSONObject(index);


                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            } else {
                               View c=otherBox.getChildAt(k);
                                CheckBox b =c.findViewById(R.id.cb);
                                b.setChecked(false);
                            }
                        }


                        for(int j=0;j<giftBox.getChildCount();j++){
                                View vc = giftBox.getChildAt(j);
                                CheckBox cb =vc.findViewById(R.id.cb);
                                cb.setChecked(false);
                            }

                    }






                }
            });
        }




    }


    //动态添加 checkbox other
    public void renderOtherList() throws JSONException {
        JSONArray arr=   cInfo.getJSONArray("no_gift_type");
        otherBox.removeAllViews();
        Log.i("arr长度::", arr.toString());

        for (int i=0;i<arr.length();i++){
            View view =View.inflate(this,R.layout.checkbox_item,null);
            TextView tv =(TextView) view.findViewById(R.id.checkboxname);
            CheckBox cb =(CheckBox) view.findViewById(R.id.cb);


            int num=arr.getJSONObject(i).getInt("status");
            if(num == 1){
                cb.setChecked(false);
            }else {
                index=i;

                cb.setChecked(true);
            }



            tv.setText(arr.getJSONObject(i).getString("typename"));
            otherBox.addView(view);

        }


    }

//    动态添加checkBox giftList
    public void renderGiftList() throws JSONException {
        JSONArray arr=   cInfo.getJSONArray("gift_type");
        Log.i("arr长度::", arr.toString());
        giftBox.removeAllViews();
        for (int i=0;i<arr.length();i++){
            View view =View.inflate(this,R.layout.checkbox_item,null);
            TextView tv =(TextView) view.findViewById(R.id.checkboxname);
            CheckBox cb =(CheckBox) view.findViewById(R.id.cb);
            int num=arr.getJSONObject(i).getInt("status");
            if(num == 1){
                cb.setChecked(false);
            }else {
                index=i;

                cb.setChecked(true);
            }

            tv.setText(arr.getJSONObject(i).getString("typename"));
            giftBox.addView(view);

        }






    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        p=new ProgressDialog(this);
        SharedPreferences sp =getSharedPreferences("userinfo",MODE_PRIVATE);

        count = Integer.parseInt(sp.getString("countDownSeconds","")) ;

        timer= new CountDownTimer( count*1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                Log.i("ssss",  String.valueOf(millisUntilFinished));

                netCall.setText("请等待"+ String.valueOf(count)+"秒后自动开始回访");
                count--;
            }

            @Override
            public void onFinish() {

                count = Integer.parseInt(sp.getString("countDownSeconds","")) ;
                 timer.cancel();
                 netCall.setClickable(true);
                 submitBtn.setClickable(true);
                 netCall.setText("网络回访");

                p.setMessage("呼叫中...");
                p.setCancelable(false);
                p.show();

                netCallback();
            }


        };

        Intent intent =getIntent();
        id=intent.getStringExtra("id");
//        Toast.makeText(getApplicationContext(),"Id:"+id,Toast.LENGTH_SHORT).show();
        caller=intent.getStringExtra("caller");
        mobile=intent.getStringExtra("mobile");



        temContext=this;
        this.init();

        this.requestDetail();

        netCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(Detail.this, "点击了", Toast.LENGTH_SHORT).show();
                p.setProgressStyle(ProgressDialog.STYLE_SPINNER);

                p.setMessage("呼叫中...");
                p.setCancelable(false);
                p.show();



                netCallback();
            }
        });


//        初始进入(无论是 刷新列表 或 自动拨打) 需监听 点击事假 触发回访接口
    }

    public void netCallback() {



        (new Thread(){
            @Override
            public void run() {




                SharedPreferences sp = getSharedPreferences("userinfo",MODE_PRIVATE);
//                        get 请求
                //实例化  里面可能会出现异常，需要try  catch
                OkHttpClient client = new OkHttpClient();
                //建立一个Request  通过Builder方法.Url里面填的就是json网址.build创建

//                http://49.234.94.134:8081/ccapp/callcenter/makeCall?calllist_id=1&callnumber=13701470807

//                String path="http://wxwork.gzsg.cn/wxwork/callcenter/setCallType";
                String path=MedicalCareApi.newPath+"callcenter/makeCall";
                Log.i("path::", path);

//                        Request request = new Request.Builder().url(path).build();
                Request.Builder reqBuild = new Request.Builder();
                HttpUrl.Builder urlBuilder =HttpUrl.parse(path)
                        .newBuilder();
                urlBuilder.addQueryParameter("calllist_id", id);
                urlBuilder.addQueryParameter("callnumber", sp.getString("myPhone",""));

                reqBuild.url(urlBuilder.build());
                Request request = reqBuild.build();



                try {

                    //Response是okhttp实例化，并且调用Request。执行后返回的结果
                    Response response = client.newCall(request).execute();
                    String s = response.body().string();//获取到的json数据

                    Log.i("回访信息::", s);

                    JSONObject res =  new JSONObject(s);//转成json

                    int code = res.getInt("code");
                     err= res.getString("msg");
                    if(code ==  0){

                        Message msg =new Message();
                        msg.what=4;
                        mHandler.sendMessage(msg);



                    }else {
                        Message msg =new Message();
                        msg.what=4;
//                        err=err;
                        mHandler.sendMessage(msg);

                    }





                } catch (Exception e) {
                    Message msg =new Message();
                    msg.what=4;
                    err="网络错误,稍后重试！";
                    mHandler.sendMessage(msg);

                }















            }
        }).start();






    }






    public void init() {


        SharedPreferences sp= getSharedPreferences("userinfo",MODE_PRIVATE);
        isAutoDial=   sp.getString("isAutoDial","0"); // 0 1
        isRefreshList=  sp.getString("isRefreshList","0"); // 0 1

        countDownSeconds= Integer.parseInt(sp.getString("countDownSeconds","5")) ; // 5 - 10

        String phoneNum=sp.getString("myPhone","");



        Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);

        netCall=(Button)findViewById(R.id.netCall);
        addWX = (Button)findViewById(R.id.addWX);

//        addWX.setText("一键加微信");

        addWX.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Boolean flg=isWeixinAvilible(temContext);
                Boolean flg = true;
                if(flg){
                    openWX();
                }else {
                    Toast.makeText(Detail.this, "系统检测到您尚未安装微信，请安装后再试!", Toast.LENGTH_SHORT).show();
                }
            }
        });


        
        back=(Button) findViewById(R.id.back);
        customInfo=(TextView) findViewById(R.id.customInfo);
        rg=(RadioGroup)findViewById(R.id.timeRg);
        submitBtn=(Button)findViewById(R.id.submitBtn);

        checkNum =(TextView)findViewById(R.id.mark);

        memo=(EditText)findViewById(R.id.memo);
        timePicker=(TextView)findViewById(R.id.timePicker);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @SuppressLint("WrongConstant")
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                LinearLayout l1=(LinearLayout) findViewById(R.id.codeTypeL);
                LinearLayout l2=(LinearLayout) findViewById(R.id.pickerL);
                switch(checkedId){
                    case R.id.r1:
                        isC="1";
                        l1.setVisibility(0);
                        l2.setVisibility(0);


                        break;
                    case R.id.r2:
                         isC="0";
                        l1.setVisibility(8);
                        l2.setVisibility(8);
                        break;
                }
            }
        });

        submitBtn.setOnClickListener(new View.OnClickListener() {



            @Override
            public void onClick(View v) {
                if( !(giftb || otherb) ){
                    Toast.makeText(Detail.this, "请至少选择一个项目!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(item==null){
                    Toast.makeText(Detail.this, "请至少选择一个项目!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(isC.equals("1")){
                    if(mydate.equals("")){
                        Toast.makeText(Detail.this, "请点击选择日期!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                toSubmit();



            }


        });

        timePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                DatePickerDialog.OnDateSetListener onDateSetListener;

                new DatePickerDialog(Detail.this, onDateSetListener, mYear, mMonth, mDay).show();
            }
        });

//        phoneCall=(Button) findViewById(R.id.phoneCall);
//        phoneCall.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                Intent intent = new Intent(Intent.ACTION_DIAL);
//                Log.i("phone:::", mobile);
//                Uri data = Uri.parse("tel:" + mobile);
//                intent.setData(data);
//                startActivity(intent);
//
//
//            }
//        });


    }

    private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            mYear = year;
            mMonth = month;
            mDay = dayOfMonth;
            String days;
            if (mMonth + 1 < 10) {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append("-").append("0").
                            append(mMonth + 1).append("-").append("0").append(mDay).append("").toString();
                } else {
                    days = new StringBuffer().append(mYear).append("-").append("0").
                            append(mMonth + 1).append("-").append(mDay).append("").toString();
                }

            } else {
                if (mDay < 10) {
                    days = new StringBuffer().append(mYear).append("-").
                            append(mMonth + 1).append("-").append("0").append(mDay).append("").toString();
                } else {
                    days = new StringBuffer().append(mYear).append("-").
                            append(mMonth + 1).append("-").append(mDay).append("").toString();
                }

            }
            Boolean bl= null;
            try {
                bl = isOverToday(mYear,mMonth,mDay);
                if(bl){
                    timePicker.setText(days);
                    mydate=days;
                }else {
                    timePicker.setText("点击选择");
                    mydate="";
                    Toast.makeText(Detail.this, "预约日期为今日或今日后!", Toast.LENGTH_SHORT).show();

                }
            } catch (ParseException e) {
                e.printStackTrace();
            }


        }


    };

//  打开微信
    public void openWX(){
//           将电话添加到剪切板
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", mobile);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);

            Toast.makeText(Detail.this, "号码复制成功", Toast.LENGTH_SHORT).show();

            new Thread(){
                @Override
                public void run() {
                    // TODO Auto-generated method stub

                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Intent lan = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setComponent(lan.getComponent());
                    startActivity(intent);
                }
            }.start();




        } catch (Exception e) {

        }


    }

    public  boolean isWeixinAvilible(Context context) {

        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager

        List pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
//        Log.i("pinfo", pinfo.toString());
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).toString();
                if (pn.contains("com.tencent.mm")) {
//                    Log.i("pinfo999", pn);
                    return true;
                }
            }
        }
        return false;
    }
    
    
    

    public Boolean isOverToday(int year,int month,int day) throws ParseException {


//         昨天的日期

       Calendar cal=Calendar.getInstance();

       cal.add(Calendar.DATE,-1);

       String d=new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

        Date date1= sdf1.parse(d);

        Log.i("ss", date1.toString());

//     传入的日期

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        int realm= month +1;

        String dateString=year+"-"+realm+"-"+day;

        Date date2=sdf.parse(dateString);



        if(date2.getTime()>date1.getTime()) {

            Log.i("err", "大");
//            Toast.makeText(Detail.this,String.valueOf(date2.getTime())+"比"+String.valueOf(date1.getTime()) , Toast.LENGTH_SHORT).show();

           return true;
        }

        else {

//            Toast.makeText(Detail.this, String.valueOf(date2.getTime())+"比"+String.valueOf(date1.getTime()), Toast.LENGTH_SHORT).show();
            Log.i("err", "小");
           return false;
        }

    }

    public void toSubmit(){
//        http://wxwork.gzsg.cn/wxwork/callcenter/setCallType?hosId=1&userId=xxx&managerId=xxx&callId=1&group_id=1&
        // caller=%E6%9D%8E%E6%B5%A9&callnumber=18951835269&
        // memo=%E6%B5%8B%E8%AF%95%E5%A4%87%E6%B3%A8&type=14&isConfirm=1&mydate=2021-11-10&time=3

        p.setMessage("提交中...");
        p.setCancelable(false);
        p.show();

        Thread myT = new Thread(){
            @Override
            public void run() {
                SharedPreferences sp = getSharedPreferences("userinfo",MODE_PRIVATE);
//                        get 请求
                //实例化  里面可能会出现异常，需要try  catch
                OkHttpClient client = new OkHttpClient();
                //建立一个Request  通过Builder方法.Url里面填的就是json网址.build创建

//                String path="http://wxwork.gzsg.cn/wxwork/callcenter/setCallType";
                String path=MedicalCareApi.newPath+"callcenter/setCallType";
                Log.i("path::", path);

//                        Request request = new Request.Builder().url(path).build();
                Request.Builder reqBuild = new Request.Builder();
                HttpUrl.Builder urlBuilder =HttpUrl.parse(path)
                        .newBuilder();
                urlBuilder.addQueryParameter("hosId", "1");
                urlBuilder.addQueryParameter("userId", sp.getString("userId",""));
                urlBuilder.addQueryParameter("managerId", sp.getString("managerId",""));
                urlBuilder.addQueryParameter("callId", id);
//
                urlBuilder.addQueryParameter("callerId", sp.getString("callerId",""));
                urlBuilder.addQueryParameter("group_id", sp.getString("groupId",""));


                try {
                    Log.i("item", item.getString("id"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }


//                urlBuilder.addQueryParameter("hosId", "1");
//                urlBuilder.addQueryParameter("userId", "xxx");
//                urlBuilder.addQueryParameter("managerId", "xxx");
//                urlBuilder.addQueryParameter("callId", "1");
//                urlBuilder.addQueryParameter("group_id", "1");

                urlBuilder.addQueryParameter("caller", caller);
                urlBuilder.addQueryParameter("callnumber", mobile);

                if(isC.equals("1")){
                        urlBuilder.addQueryParameter("memo", memo.getText().toString());
                        try {
                            urlBuilder.addQueryParameter("type", item.getString("id"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        urlBuilder.addQueryParameter("isConfirm", isC);
                        urlBuilder.addQueryParameter("time", timeT);
                        urlBuilder.addQueryParameter("mydate", mydate);
                        urlBuilder.addQueryParameter("isConfirm", isC);
                }else {
                        urlBuilder.addQueryParameter("memo", memo.getText().toString());
                        urlBuilder.addQueryParameter("isConfirm", isC);


                    try {
                        urlBuilder.addQueryParameter("type", item.getString("id"));
                        urlBuilder.addQueryParameter("time", timeT);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }


               String str = "hosId=1&userId="+sp.getString("userId","")+"&callId="+id+"&group_id="+sp.getString("groupId","")+
                       "&caller="+caller+"&callnumber="+mobile+"&callerId="+sp.getString("callerId","");


                Log.i("参数", str);

                reqBuild.url(urlBuilder.build());
                Request request = reqBuild.build();



                try {

                    //Response是okhttp实例化，并且调用Request。执行后返回的结果
                    Response response = client.newCall(request).execute();
                    String s = response.body().string();//获取到的json数据

                    Log.i("错误99966", s );

                    JSONObject res =  new JSONObject(s);//转成json

                    Log.i("string::9999",res.toString() );

                    int code = res.getInt("code");

                    err= res.getString("msg");
                    if(code == 0){
                        Message msg =new Message();
                        msg.what=2;
                        mHandler.sendMessage(msg);
                    }else{
                        Message msg =new Message();
                        msg.what=4;
                        mHandler.sendMessage(msg);


                    }





                } catch (Exception e) {

                }
            }
        };
        myT.start();




    }

    public void requestNext(){





    }


    public void requestDetail() {

//        http://wxwork.gzsg.cn/wxwork/callcenter/queryCallInfo?hosId=1&userId=xxx&managerId=xxx&callId=1&group_id=1
//        http://wxwork.gzsg.cn/wxwork/callcenter/queryCallInfo?hosId=1&userId=xxx&managerId=xxx&callId=1&group_id=1
        Thread myT = new Thread(){
            @Override
            public void run() {
                SharedPreferences sp = getSharedPreferences("userinfo",MODE_PRIVATE);
//                        get 请求
                //实例化  里面可能会出现异常，需要try  catch
                OkHttpClient client = new OkHttpClient();
                //建立一个Request  通过Builder方法.Url里面填的就是json网址.build创建

//                String path="http://wxwork.gzsg.cn/wxwork/callcenter/queryCallInfo";
                  String path =MedicalCareApi.newPath+"callcenter/queryCallInfo";
                Log.i("path::", path);

//                        Request request = new Request.Builder().url(path).build();
                Request.Builder reqBuild = new Request.Builder();
                HttpUrl.Builder urlBuilder =HttpUrl.parse(path)
                        .newBuilder();
                urlBuilder.addQueryParameter("hosId", "1");
                urlBuilder.addQueryParameter("userId", sp.getString("userId",""));
                urlBuilder.addQueryParameter("managerId", sp.getString("managerId",""));
                urlBuilder.addQueryParameter("callId", id);
                urlBuilder.addQueryParameter("group_id", sp.getString("groupId",""));

//                urlBuilder.addQueryParameter("hosId", "1");
//                urlBuilder.addQueryParameter("userId", "xxx");
//                urlBuilder.addQueryParameter("managerId", "xxx");
//                urlBuilder.addQueryParameter("callId", "1");
//                urlBuilder.addQueryParameter("group_id", "1");


                reqBuild.url(urlBuilder.build());
                Request request = reqBuild.build();



                try {

                    //Response是okhttp实例化，并且调用Request。执行后返回的结果
                    Response response = client.newCall(request).execute();
                    String s = response.body().string();//获取到的json数据

                    Log.i("详情地址::", s);
                    cInfo =  new JSONObject(s);//转成json



                    Message msg =new Message();

                    mHandler.sendMessage(msg);




                } catch (IOException | JSONException e) {

                }
            }
        };
        myT.start();


    }
}